package com.Yukiha.gachamod.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

public class ModelJsonLoader {
    private static final Logger LOGGER = LogManager.getLogger("GachaMod");
    private static final Path AUTH_MODEL_DIR = Path.of("config/yes_steve_model/auth");
    private static final Path OUTPUT_FILE = Path.of("config/gachamod/models.json");

    public static void generateModelJsonByRarity() {

        try {
            if (!Files.exists(AUTH_MODEL_DIR)) {
                LOGGER.error("[GachaMod] 模型目录不存在: {}", AUTH_MODEL_DIR);
                return;
            }

            JsonObject output = new JsonObject();

            try (Stream<Path> folders = Files.list(AUTH_MODEL_DIR)) {
                folders.filter(Files::isDirectory).forEach(rarityFolder -> {
                    String rarity = rarityFolder.getFileName().toString();
                    JsonArray models = new JsonArray();

                    try (Stream<Path> entries = Files.list(rarityFolder)) {
                        entries.forEach(entry -> {
                            if (Files.isDirectory(entry)) {
                                // 模型是一个文件夹：名字就是模型名
                                models.add(entry.getFileName().toString());
                            } else if (entry.toString().endsWith(".ysm")) {
                                // 模型是一个单独的 .json 文件
                                String name = entry.getFileName().toString().replace(".ysm", "");
                                models.add(name);
                            } else if (entry.toString().endsWith(".json")) {
                                // 模型是一个单独的 .json 文件
                                String name = entry.getFileName().toString().replace(".json", "");
                                models.add(name);
                            }
                        });
                    } catch (IOException e) {
                        LOGGER.error("[GachaMod] 无法读取 " + rarityFolder + " 中的模型");
                    }

                    if (models.size() > 0) {
                        output.add(rarity, models);
                    }
                });
            }

            Files.createDirectories(OUTPUT_FILE.getParent());

            try (Writer writer = Files.newBufferedWriter(OUTPUT_FILE)) {
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                gson.toJson(output, writer);
            }

            LOGGER.info("[GachaMod] ✔ 成功生成模型池，共包含稀有度：" + output.keySet());
        } catch (IOException e) {
            LOGGER.error("[GachaMod] ❌ 写入模型配置失败: " + e.getMessage());
        }
    }

}
